<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card><el-row :gutter="20"><el-col :span="5">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" :clearable="true" @clear="getUserList()">
          <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
        </el-input>
      </el-col><el-col :span="4">
        <el-button type="primary" @click="adduser()">添加用户</el-button>
      </el-col></el-row><el-table :data="userlist" :border="true" :stripe="true">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false"><el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top"><el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top"><el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table><el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 1, 2, 5]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination></el-card><el-dialog
      title="添加用户"
      :visible.sync="addUserVisible"
      width="50%"
      @close="closeAddUser()">
      <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserBtn()">确 定</el-button>
      </span>
    </el-dialog><el-dialog
      title="修改用户"
      :visible.sync="modUserVisible"
      width="50%"
      @close="closeModUser()">
      <el-form :model="modUserForm" :rules="modUserRules" ref="modUserRef" label-width="100px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="modUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="modUserBtn()">确 定</el-button>
      </span>
    </el-dialog><el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%">
      <div>
        <p>当前用户：{{userinfo.username}}</p>
        <p>当前角色：{{userinfo.role_name}}</p>
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 11
      },
      userlist: [],
      total: 0,
      addUserVisible: false,
      modUserVisible: false,
      setRoleDialogVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名的长度在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      modUserForm: {
        email: '',
        mobile: ''
      },
      modUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      modifyCurrentId: 0,
      userinfo: {},
      rolesList: [],
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      let res = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)
      if (res.data.meta.status !== 200) {
        return this.$message.error(res.data.meta.msg)
      } else if (res.data.meta.status === 200) {
        this.$message.success(res.data.meta.msg)
        this.userlist = res.data.data.users
        this.total = res.data.data.total
      }
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pagenum = newSize
      this.getUserList()
    },
    async userStateChanged(userinfo) {
      // console.log(userinfo.mg_state)
      let res = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      // console.log(res)
      if (res.data.meta.status !== 200) {
        return this.$message.error(res.data.meta.msg)
      } else if (res.data.meta.status === 200) {
        this.$message.success(res.data.meta.msg)
      }
    },
    adduser() {
      this.addUserVisible = true
    },
    closeAddUser() {
      this.$refs.addUserRef.resetFields()
    },
    closeModUser() {
      this.$refs.modUserRef.resetFields()
    },
    addUserBtn() {
      this.$refs.addUserRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return this.$message.error('添加失败')
        if (valid) {
          let res = await this.$http.post('users', this.addUserForm)
          console.log(res)
          if (res.data.meta.status !== 201) {
            return this.$message.error(res.data.meta.msg)
          } else if (res.data.meta.status === 201) {
            this.$message.success(res.data.meta.msg)
            this.addUserVisible = false
            this.getUserList()
          }
        }
      })
    },
    removeUserById(id) {
      // console.log(id);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await this.$http.delete(`users/${id}`)
        console.log(res)
        this.$message.success(res.data.meta.msg)
        this.getUserList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    async modifyUserById(id) {
      this.modifyCurrentId = id
      let res = await this.$http.get(`users/${id}`)
      // console.log(res)
      this.modUserForm.email = res.data.data.email
      this.modUserForm.mobile = res.data.data.mobile
      this.modUserVisible = true
    },
    // 修改用户信息
    async modUserBtn() {
      this.$refs.modUserRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return this.$message.error('添加失败')
        if (valid) {
          let res = await this.$http.put(`users/${this.modifyCurrentId}`, { email: this.modUserForm.email, mobile: this.modUserForm.mobile })
          if (res.data.meta.status !== 200) return this.$message.error(res.data.meta.msg)
          if (res.data.meta.status === 200) {
            // console.log(this)
            this.$message.success(res.data.meta.msg)
            this.modUserVisible = false
            this.$refs.modUserRef.resetFields()
            this.getUserList()
          }
        }
      })
    },
    async setRole(userinfo) {
      this.userinfo = userinfo
      let res = await this.$http.get('roles')
      if (res.data.meta.status !== 200) return this.$message.error(res.data.meta.msg)
      if (res.data.meta.status === 200) {
        // console.log(res.data.data)
        this.rolesList = res.data.data
        this.$message.success(res.data.meta.msg)
        this.setRoleDialogVisible = true
      }
    },
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }

      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 20px;
}
</style>
